/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.api.listener;

import java.util.List;
import java.util.Objects;

import org.activiti.engine.EngineServices;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.impl.ActivitiEntityEventImpl;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.koron.workflow.api.bean.RelationBean;
import com.koron.workflow.api.bean.TimerBean;
import com.koron.workflow.api.mapper.TimerMapper;
import com.koron.workflow.api.service.ActivitiService;
import com.koron.workflow.api.service.AutoCompleteService;
import com.koron.workflow.api.service.RelationService;
import com.koron.workflow.api.service.TaskListService;
import com.koron.workflow.common.exception.WorkflowException;
import com.koron.workflow.common.util.SessionFactoryLocal;
import com.koron.workflow.common.util.SpringContextHolder;

/**
 * 任务创建
 * @author bin
 *
 */
public class TaskCreatedListener extends ProcessListenerAdapter{
	
	private static Logger log = LoggerFactory.getLogger(TaskCreatedListener.class);
	
	private ActivitiService activitiService = SpringContextHolder.getBean(ActivitiService.class);
	
	private TaskListService taskListService = SpringContextHolder.getBean(TaskListService.class);
	
	private RelationService relationService = SpringContextHolder.getBean(RelationService.class);
	
	@Override
	@SuppressWarnings("unchecked")
	public void taskCreatetd(ActivitiEvent event) {
		log.info("任务已经创建....");
		if(event instanceof ActivitiEntityEventImpl) {
			ActivitiEntityEventImpl activitiEntity = (ActivitiEntityEventImpl) event;
			Object object = activitiEntity.getEntity();
			if(object instanceof TaskEntity) {
				TaskEntity entity = (TaskEntity) object;
				EngineServices engineServices = event.getEngineServices();
				RuntimeService runtimeService = engineServices.getRuntimeService();
				String operation = (String) runtimeService.getVariable(event.getExecutionId(), "operation");
				if(operation != null && "1".equals(operation)) {
					return;
				}
				SessionFactory factory = SessionFactoryLocal.get();
				String title = (String) runtimeService.getVariable(event.getExecutionId(), "title");
				if(!activitiService.isDraftNode(entity)) {  //假如不是起草节点
					if(activitiService.isApprovalNode(entity)) {
						String mode = activitiService.getCirculationMode(entity);
						String variableName = "Loop" + entity.getTaskDefinitionKey().replaceAll("-", "") + "_User_List";
						List<String> usersList = runtimeService.getVariable(event.getExecutionId(), variableName, List.class);
						Object loopCounter = runtimeService.getVariable(event.getExecutionId(), "loopCounter");
						//先删除候选人员列表
						activitiService.deleteCandidateUsers(entity.getId());
						//处理人为空跳过
						if(activitiService.isNullOperatorSkip(entity, usersList)) {
							TimerBean timer = new TimerBean(entity.getId(), 0, 1, AutoCompleteService.TYPE_NULLDEFSKIP);
							factory.getMapper(TimerMapper.class).addTimer(timer);
							return;
						}
						if(usersList.size() == 0) {
							throw new WorkflowException("处理人为空,请设置该节点的处理人员");
						}
						//身份重复跳过
						if(activitiService.isDoubleSkip(entity, usersList, mode, Objects.toString(loopCounter, "0"))) {
							TimerBean timer = new TimerBean(entity.getId(), 0, 1, AutoCompleteService.TYPE_DUPIDSKIP);
							factory.getMapper(TimerMapper.class).addTimer(timer);
							return;
						} 
						if("2".equals(mode) || "3".equals(mode)) { //串行 或者 会审
							int index = loopCounter == null ? 0 : Integer.parseInt(Objects.toString(loopCounter));
							//添加关系列表
							activitiService.addCandidateUser(entity.getId(), usersList.get(index));
							relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, usersList.get(index), entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
						}else {
							for(String user : usersList) {
								//添加关系列表
								activitiService.addCandidateUser(entity.getId(), user);
								relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, user, entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
							}
						}
						//添加任务列表
						taskListService.addTaskList(factory, entity, title);
					}
					//假如是子流程节点
					if(activitiService.isSubTaskNode(entity)) {
						activitiService.addCandidateUser(entity.getId(), "system_operation");
						relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_HANDLE, "system_operation", entity.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_UNHANDLE), null);
						//添加任务列表
						taskListService.addTaskList(factory, entity, title);
					}
				} else {
					//假如该节点是起草节点 添加流程起草人节点关系
					String userId = Authentication.getAuthenticatedUserId();
					//添加关系列表
					activitiService.addCandidateUser(entity.getId(), userId);
					relationService.addRelation(factory, 512, new RelationBean(RelationBean.R_START, userId, event.getProcessInstanceId(), entity.getId(), RelationBean.STATUS_HANDLED), null);
					//添加任务列表
					taskListService.addTaskList(factory, entity, title, 2);
				}
			}
		}
	}
}
